const BaseComponent = require('../prototype/baseComponent');
const AdsModel = require("../models").Ads;
const AdsItemsModel = require("../models").AdsItems;
const formidable = require('formidable');
const { service, validatorUtil, siteFunc } = require('../../../utils');
const shortid = require('shortid');
const validator = require('validator');
const bodyParser = require('body-parser');
const fs = require('fs');

let requestLib = require('request');
// 设置为使用cookie
// request.defaults({jar: true});

let j = requestLib.jar();
let request = requestLib.defaults({jar:j});

function checkFormData(req, res, fields) {
  let errMsg = '';
  if (fields._id && !siteFunc.checkCurrentId(fields._id)) {
    errMsg = res.__("validate_error_params");
  }
  if (!validator.isLength(fields.name, 2, 15)) {
    errMsg = res.__("validate_rangelength", { min: 2, max: 15, label: res.__("label_ads_name") });
  }
  if (!validator.isLength(fields.comments, 5, 30)) {
    errMsg = res.__("validate_rangelength", { min: 5, max: 30, label: res.__("label_comments") });
  }
  if (errMsg) {
    throw new siteFunc.UserException(errMsg);
  }
}


class MiaoSha {
  constructor(){

  }


  /**
   * 登录 于秒杀无用的接口
   **/
  async login(req, res, next) {
    try {

      let body = req.body;

      console.log("~~~~MiaoSha~~~~login",body);
      let username = body.username;
      let password = body.password;
      let activity_id = body.activity_id;
      let project_id = body.project_id;

      // let username = 13606213208;      // 13606213208
      // let password = 0;                // xw123456
      // let activity_id = 12788;
      // let project_id = 32856;

      // 向外发送请求

      // http://sale13776.wx.leju.com/activity/sale/index.html?project_id=32856&activity_id=13776
      // http://weixin.leju.com/activity/sale/login.html?project_id=32856&activity_id=13774

      await request({
        url: `http://sale${activity_id}.wx.leju.com/activity/sale/do_login.html`,
        // url: `http://weixin.leju.com/activity/sale/do_login.html`,
        method: "POST",
        json: true,
        headers: {
          "content-type": "application/x-www-form-urlencoded",
          // "hosts": "sale12788.wx.leju.com",
          // "content-type": "application/x-www-form-urlencoded",
        },
        form: {
          mobile: username,
          image_code:'',
          code:'',
          card:'',
          name:'',
          activity_id: activity_id,
          project_id: project_id,
        }
      }, function(error, response, body) {
        console.log("~~~~MiaoSha~~~~login success");
        console.log("~~~~MiaoSha~~~~login success :::",response.headers['set-cookie']);

        if (!error && response.statusCode == 200) {
          console.log("~~~~MiaoSha~~~~login success 200 body",body);
        }

        let cookie = response.headers['set-cookie'];

        console.log("!!!!body.cookie!!!!");
        console.log(cookie);
        console.log(cookie instanceof Array);

        // let reg = /(?=sale_user_login_token=)(\S*)(?=;)/;
        let reg = /(sale_user_login_token=\S*;)/;
        let sale_user_login_token = "";
        cookie.forEach((item,i)=>{
          let regResult = item.match(reg);
          console.log("!!!!regResult!!!!");
          console.log(regResult);
          if(regResult){
            sale_user_login_token = regResult[0];
          }
        });

        console.log("!!!!sale_user_login_token!!!!");
        console.log(sale_user_login_token);

        // res.send(body);
        let result = {
          responseBody: body,
          cookie : response.headers['set-cookie'],
          sale_user_login_token : sale_user_login_token,
        };

        res.send(result);

      });
      // 返回数据
      // res.send(body);
    }catch(err){
      console.log(err);
      res.send(siteFunc.renderApiErr(req, res, 500, err, 'getlist'))
    }
  };

  async encode (req, res, next){
    try {

      let body = req.body;

      console.log("~~~~MiaoSha~~~~encode",body);
      let username = body.userMsg.username;
      let password = body.userMsg.password;
      let activity_id = body.userMsg.activity_id;
      let project_id = body.userMsg.project_id;

      // 向外发送请求
      await request({
        url: `http://weixin.leju.com/activity/sale/encode.html`,
        method: "POST",
        json: true,
        headers: {
          "content-type": "application/x-www-form-urlencoded",
          // "cookie": cookie
        },
        form: {
          mobile: username,
          password: password,
          activity_id: activity_id,
          project_id: project_id,
        }
      }, function(error, response, body) {
        console.log("~~~~MiaoSha~~~~encode success");
        console.log("~~~~MiaoSha~~~~encode success :::",body);

        // var cookie = request.cookie('MC_STORE_ID=66860');
        // fs.writeFile(
        //   `/Users/zhaoqi/Downloads/encode_cookieDemo_${new Date().getTime()}.json`,
        //   JSON.stringify(cookie),
        //   'utf8',
        //   function(error){
        //   if(error){
        //     console.log(error);
        //     return false;
        //   }
        //   console.log('写入成功');
        // });

        // console.log("!!!!__dirname!!!!",__dirname);

        // fs.writeFile(`/Users/zhaoqi/Downloads/encode_response_${new Date().getTime()}.json`,JSON.stringify(response),'utf8',function(error){
        //   if(error){
        //     console.log(error);
        //     return false;
        //   }
        //   console.log('写入成功');
        // })

        // for(let key in response.headers){
        //   console.log('key : ',key);
        // }

        if (!error && response.statusCode == 200) {
          console.log("~~~~MiaoSha~~~~encode success 200 body",body);
        }

        // res.send(body);

        // {
        //   "mobile":"YjNiMjA4NGJNVE0yTURZeU1UTXlNRGc9ZDI2YQ==",
        //   "password":"MzgwMTE1ZjZlSGN4TWpNME5UWT02NDEz",
        //   "key":"NzEzMDEyNmRjMkZzWlRFeU56ZzRMbmQ0TG14bGFuVXVZMjl0ODZmOA=="
        // }

        let result = {
          responseBody: body,
        };

        res.send(result);

      });
      // 返回数据
      // res.send(body);
    }catch(err){
      console.log(err);
      res.send(siteFunc.renderApiErr(req, res, 500, err, 'getlist'))
    }
  }

  /**
   * 查看收藏，可以检查是否登录成功
   **/
  async myCollect (req, res, next){
    try {

      let body = req.body;

      console.log("~~~~MiaoSha~~~~myCollect",body);
      let username = body.userMsg.username;
      let password = body.userMsg.password;
      let activity_id = body.userMsg.activity_id;
      let project_id = body.userMsg.project_id;

      // let cookie = body.cookie;

      // console.log('!!!cookieFromBody!!!',cookie);

      // let cookie = {
      //   // touch_city: 'FGBVcX9%2B66aV4klAwKNnycFvBNlppBL6%2FaQd9O8rCig%3D',
      //   // verfiy_code_user: '4vdBfF%2BpoxTb8h1MrwyIkfOK3fpJ3ngKsTcZ6rQd%2FO4%2BUC7Xhvu080E9h%2B5a0i35',
      //   // gatheruuid: '1545ou28a5276382',
      //   // s2: '1545287076436_WBGD18',
      //   // co: '1639893276437_84EW2Y',
      //
      //   // M_CITY: 'suzhou',
      //
      //   M_AUTH: 'f69872979d7579c6b0f7f3bc9fe31da884d0081c',
      //   M_USER: 'eNo1UMtqAzEM%2FBrnUijyc62DD7tdk7h0ne4rdHMJrB%2FQ0B%2Fo39dxWyHQMBpphA7DbXW9YVBDIOOo2KGQs518O1hDrCAdEgRiG9IxovHGgGpKGQMEypUUuujfT2dvzXb3n8O9Ff746i8Wvpd1uqaVrsvHl5%2BOAa%2B9Y9tIeF%2ByDNmhdW%2BmgHmbF1fM4JlrbDQFeKJSSKYlZ7z03byc3NSbCufzOr1Yk3JsdNijTIhJ5T1HCQr3mIMKjcpQtZ3zvYmCRh0i6gywMxAJNQCiTiFrwZr0OMD51tX94%2FhbH0x9QOX%2B0fJn%2FgNnAlOq',
      //
      //   // M_KEY: 'NDA0MmJhOGNjMkZzWlRFeU56ZzRMbmQ0TG14bGFuVXVZMjl0WHpJMU9USXdNREE9M2NjMw%3D%3D',
      //   // M_INFO: '%7B%22uid%22%3A%2220000004923962%22%2C%22username%22%3A%22%5Cu4e50%5Cu7c89_20181122090136548%22%2C%22isThird%22%3Afalse%2C%22phone%22%3A%22136%2A%2A%2A%2A3208%22%2C%22headurl%22%3A%22http%3A%5C%2F%5C%2Fsrc.house.sina.com.cn%5C%2Fimp%5C%2Fimp%5C%2Fdeal%5C%2F17%5C%2F43%5C%2F6%5C%2Fd6dd6705ee15ef8e7687a7b4c75_p10_mk10.png%22%2C%22sinaid%22%3A%22%22%2C%22qqid%22%3A%22%22%2C%22type%22%3A%220%22%2C%22iscard%22%3Afalse%7D',
      //   // M_UID: '20000004923962',
      //   // M_ITSOURCE: 'efd78cbd5e99e6fbfd5069bdfc6c76f0',
      //   // M_SPRING: 'YzRjYTQyMzhNUT09YjkyMw%3D%3D',
      //   // M_TICKET: 'OGE5YmVmZTJjMkZzWlRFeU56ZzRMbmQ0TG14bGFuVXVZMjl0WHpFMU5EVXlPRFV6TWpOZk1qQXdNREF3TURRNU1qTTVOakk9ZjRiZQ%3D%3D',
      //
      //   // sale_user_login_token: 'lLPnbrm1Blb6nYs96XhsHRzt4Qtsx3uR%2FkCuzDopLAGICCscmOC%2BdzGkS19YBnviPlAu14b7tPNBPYfuWtIt%2BQ%3D%3D',
      //   // game_uuid_login_count: '0',
      //   // uuid: 'LwqZeJ5qryFiqPa%2BEcPEQvAcZ2fOi1WLICM6KlYY4e8%2BUC7Xhvu080E9h%2B5a0i35',
      //   // extern_host: 'sale12788.wx.leju.com',
      //   // cy_ec_id: 'b3dce4dc6857ca31c0046260530a488d',
      // };

      let cookie = body.userMsg.ssoCookie;
      
      let cookieString = '';

      for (let k in cookie) {
        cookieString += `${k}=${cookie[k]}; `;
      }

      // console.log("!!!cookieString!!!",cookieString);
      

      // "Cookie": `touch_city=FGBVcX9%2B66aV4klAwKNnycFvBNlppBL6%2FaQd9O8rCig%3D; verfiy_code_user=4vdBfF%2BpoxTb8h1MrwyIkfOK3fpJ3ngKsTcZ6rQd%2FO4%2BUC7Xhvu080E9h%2B5a0i35; gatheruuid=1545ou28a5276382; s2=1545287076436_WBGD18; co=1639893276437_84EW2Y; M_CITY=suzhou; M_AUTH=f69872979d7579c6b0f7f3bc9fe31da884d0081c; M_USER=eNo1UMtqAzEM%2FBrnUijyc62DD7tdk7h0ne4rdHMJrB%2FQ0B%2Fo39dxWyHQMBpphA7DbXW9YVBDIOOo2KGQs518O1hDrCAdEgRiG9IxovHGgGpKGQMEypUUuujfT2dvzXb3n8O9Ff746i8Wvpd1uqaVrsvHl5%2BOAa%2B9Y9tIeF%2ByDNmhdW%2BmgHmbF1fM4JlrbDQFeKJSSKYlZ7z03byc3NSbCufzOr1Yk3JsdNijTIhJ5T1HCQr3mIMKjcpQtZ3zvYmCRh0i6gywMxAJNQCiTiFrwZr0OMD51tX94%2FhbH0x9QOX%2B0fJn%2FgNnAlOq; M_KEY=NDA0MmJhOGNjMkZzWlRFeU56ZzRMbmQ0TG14bGFuVXVZMjl0WHpJMU9USXdNREE9M2NjMw%3D%3D; M_INFO=%7B%22uid%22%3A%2220000004923962%22%2C%22username%22%3A%22%5Cu4e50%5Cu7c89_20181122090136548%22%2C%22isThird%22%3Afalse%2C%22phone%22%3A%22136%2A%2A%2A%2A3208%22%2C%22headurl%22%3A%22http%3A%5C%2F%5C%2Fsrc.house.sina.com.cn%5C%2Fimp%5C%2Fimp%5C%2Fdeal%5C%2F17%5C%2F43%5C%2F6%5C%2Fd6dd6705ee15ef8e7687a7b4c75_p10_mk10.png%22%2C%22sinaid%22%3A%22%22%2C%22qqid%22%3A%22%22%2C%22type%22%3A%220%22%2C%22iscard%22%3Afalse%7D; M_UID=20000004923962; M_ITSOURCE=efd78cbd5e99e6fbfd5069bdfc6c76f0; M_SPRING=YzRjYTQyMzhNUT09YjkyMw%3D%3D; M_TICKET=OGE5YmVmZTJjMkZzWlRFeU56ZzRMbmQ0TG14bGFuVXVZMjl0WHpFMU5EVXlPRFV6TWpOZk1qQXdNREF3TURRNU1qTTVOakk9ZjRiZQ%3D%3D; sale_user_login_token=lLPnbrm1Blb6nYs96XhsHRzt4Qtsx3uR%2FkCuzDopLAGICCscmOC%2BdzGkS19YBnviPlAu14b7tPNBPYfuWtIt%2BQ%3D%3D; game_uuid_login_count=0; uuid=LwqZeJ5qryFiqPa%2BEcPEQvAcZ2fOi1WLICM6KlYY4e8%2BUC7Xhvu080E9h%2B5a0i35; extern_host=sale12788.wx.leju.com; cy_ec_id=b3dce4dc6857ca31c0046260530a488d`

      // "Cookie": `
      // touch_city=FGBVcX9%2B66aV4klAwKNnycFvBNlppBL6%2FaQd9O8rCig%3D;
      // verfiy_code_user=4vdBfF%2BpoxTb8h1MrwyIkfOK3fpJ3ngKsTcZ6rQd%2FO4%2BUC7Xhvu080E9h%2B5a0i35;
      // gatheruuid=1545ou28a5276382;
      // s2=1545287076436_WBGD18;
      // co=1639893276437_84EW2Y;
      // M_CITY=suzhou;
      // M_AUTH=f69872979d7579c6b0f7f3bc9fe31da884d0081c;
      // M_USER=eNo1UMtqAzEM%2FBrnUijyc62DD7tdk7h0ne4rdHMJrB%2FQ0B%2Fo39dxWyHQMBpphA7DbXW9YVBDIOOo2KGQs518O1hDrCAdEgRiG9IxovHGgGpKGQMEypUUuujfT2dvzXb3n8O9Ff746i8Wvpd1uqaVrsvHl5%2BOAa%2B9Y9tIeF%2ByDNmhdW%2BmgHmbF1fM4JlrbDQFeKJSSKYlZ7z03byc3NSbCufzOr1Yk3JsdNijTIhJ5T1HCQr3mIMKjcpQtZ3zvYmCRh0i6gywMxAJNQCiTiFrwZr0OMD51tX94%2FhbH0x9QOX%2B0fJn%2FgNnAlOq;
      // M_KEY=NDA0MmJhOGNjMkZzWlRFeU56ZzRMbmQ0TG14bGFuVXVZMjl0WHpJMU9USXdNREE9M2NjMw%3D%3D;
      // M_INFO=%7B%22uid%22%3A%2220000004923962%22%2C%22username%22%3A%22%5Cu4e50%5Cu7c89_20181122090136548%22%2C%22isThird%22%3Afalse%2C%22phone%22%3A%22136%2A%2A%2A%2A3208%22%2C%22headurl%22%3A%22http%3A%5C%2F%5C%2Fsrc.house.sina.com.cn%5C%2Fimp%5C%2Fimp%5C%2Fdeal%5C%2F17%5C%2F43%5C%2F6%5C%2Fd6dd6705ee15ef8e7687a7b4c75_p10_mk10.png%22%2C%22sinaid%22%3A%22%22%2C%22qqid%22%3A%22%22%2C%22type%22%3A%220%22%2C%22iscard%22%3Afalse%7D;
      // M_UID=20000004923962;
      // M_ITSOURCE=efd78cbd5e99e6fbfd5069bdfc6c76f0;
      // M_SPRING=YzRjYTQyMzhNUT09YjkyMw%3D%3D;
      // M_TICKET=OGE5YmVmZTJjMkZzWlRFeU56ZzRMbmQ0TG14bGFuVXVZMjl0WHpFMU5EVXlPRFV6TWpOZk1qQXdNREF3TURRNU1qTTVOakk9ZjRiZQ%3D%3D;
      // sale_user_login_token=lLPnbrm1Blb6nYs96XhsHRzt4Qtsx3uR%2FkCuzDopLAGICCscmOC%2BdzGkS19YBnviPlAu14b7tPNBPYfuWtIt%2BQ%3D%3D;
      // game_uuid_login_count=0;
      // uuid=LwqZeJ5qryFiqPa%2BEcPEQvAcZ2fOi1WLICM6KlYY4e8%2BUC7Xhvu080E9h%2B5a0i35;
      // extern_host=sale12788.wx.leju.com;
      // cy_ec_id=b3dce4dc6857ca31c0046260530a488d`


      // 向外发送请求

      await request({
        // url: `http://sale12788.wx.leju.com/activity/sale/my_collect.html?&project_id=32856&activity_id=12788&tpl=center`,
        url: `http://sale${activity_id}.wx.leju.com/activity/sale/my_collect.html?&project_id=${project_id}&activity_id=${activity_id}&tpl=center`,
        // url: `http://weixin.leju.com/activity/sale/my_collect.html?&project_id=${project_id}&activity_id=${activity_id}&tpl=center`,
        method: "GET",
        // json: true,
        headers: {
          // "content-type": "application/x-www-form-urlencoded",
          "content-type": "text/html",
          // "Cookie": body.sale_user_login_token
          "Cookie": cookieString
        },
      }, function(error, response, body) {
        console.log("~~~~MiaoSha~~~~encode myCollect");

        if (!error && response.statusCode == 200) {
          // console.log("~~~~MiaoSha~~~~encode myCollect 200 body",body);
        }else{
          console.log("~~~~MiaoSha~~~~encode myCollect error body",body);
        }

        let result = {
          responseBody: body,
        };

        res.send(result);
      });
      // 返回数据
      // res.send(body);
    }catch(err){
      // console.log(err);
      res.send(siteFunc.renderApiErr(req, res, 500, err, 'getlist'))
    }
  }

  /**
   * 单点登录，重要，获取cookie
   **/
  async ssoLogin (req, res, next){
    // http://my.leju.com/web/sso/ssoLogin?mobile=YjNiMjA4NGJNVE0yTURZeU1UTXlNRGc9ZDI2YQ==&password=MzgwMTE1ZjZlSGN4TWpNME5UWT02NDEz&key=NzEzMDEyNmRjMkZzWlRFeU56ZzRMbmQ0TG14bGFuVXVZMjl0ODZmOA==&check_image=0&_=1543742996594&callback=Zepto1543742913380
    try {

      let body = req.body;

      console.log("~~~~MiaoSha~~~~ssoLogin",body);
      let mobile = body.encodeMsg.mobile;
      let password = body.encodeMsg.password;
      let key = body.encodeMsg.key;
      let _ = new Date().getTime();
      let check_image = 0;
      let callback = 'Zepto1543742913380';

      let cookie = body.cookie;


      let url = `http://my.leju.com/web/sso/ssoLogin?mobile=${mobile}&password=${password}&key=${key}&check_image=${check_image}&_=${_}&callback=${callback}`;
      console.log("!!!url!!!",url);

      // 向外发送请求

      await request({
        url: url,
        method: "GET",
        // json: true,
        headers: {
          // "content-type": "application/x-www-form-urlencoded",
          // "Cookie": body.sale_user_login_token,
          // "Cookie": 'gatheruuid=15b4286p93154949; M_CITY=suzhou; PHPSESSID=4pab8bnap67i7o6nreqiv4pmb5; M_SPRING=YzRjYTQyMzhNUT09YjkyMw%3D%3D; sale_user_login_token=3BAUhy2jR2wSHS4VlSv85zag%2FYv1cJ%2BpNpDCSwzFRlrAg6EM4NPt0maXF9%2FZxt0%2FPlAu14b7tPNBPYfuWtIt%2BQ%3D%3D; extern_host=sale12788.wx.leju.com; M_KEY=NDA0MmJhOGNjMkZzWlRFeU56ZzRMbmQ0TG14bGFuVXVZMjl0WHpJMU9USXdNREE9M2NjMw%3D%3D; M_INFO=%7B%22uid%22%3A%2220000004923962%22%2C%22username%22%3A%22%5Cu4e50%5Cu7c89_20181122090136548%22%2C%22isThird%22%3Afalse%2C%22phone%22%3A%22136%2A%2A%2A%2A3208%22%2C%22headurl%22%3A%22http%3A%5C%2F%5C%2Fsrc.house.sina.com.cn%5C%2Fimp%5C%2Fimp%5C%2Fdeal%5C%2F17%5C%2F43%5C%2F6%5C%2Fd6dd6705ee15ef8e7687a7b4c75_p10_mk10.png%22%2C%22sinaid%22%3A%22%22%2C%22qqid%22%3A%22%22%2C%22type%22%3A%220%22%2C%22iscard%22%3Afalse%7D; M_UID=20000004923962; M_ITSOURCE=efd78cbd5e99e6fbfd5069bdfc6c76f0; M_TICKET=NjcxYjlhMWFjMkZzWlRFeU56ZzRMbmQ0TG14bGFuVXVZMjl0WHpFMU5ETTNOREk1T1RaZk1qQXdNREF3TURRNU1qTTVOakk9MDYzOA%3D%3D',
          "Host": 'my.leju.com',
          // "Referer": 'http://sale12788.wx.leju.com/activity/sale/login.html?project_id=32856&activity_id=12788&login_type=2',
          "cache-control":"no-cache",
          // "Postman-Token": "7dc61ac5-af07-430b-86e1-e7daffeca342",
          // "User-Agent": 'PostmanRuntime/7.4.0',
          // "User-Agent": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:63.0) Gecko/20100101 Firefox/63.0',
          "Accept": "*/*",
          // "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
          // "Accept-Encoding": "gzip, deflate",
          // "Accept-Encoding": "text/html",
          "Connection": " keep-alive",
        },
      }, function(error, response, body) {
        console.log("~~~~MiaoSha~~~~ssoLogin success");
        // console.log("~~~~MiaoSha~~~~ssoLogin success body:::",body);
        // console.log("~~~~MiaoSha~~~~ssoLogin success response:::",response);
        console.log("~~~~MiaoSha~~~~ssoLogin success rawHeaders:::",response.rawHeaders);

        if (!error && response.statusCode == 200) {
          console.log("~~~~MiaoSha~~~~ssoLogin success 200 body",body);
        }

        let ssoCookie = {};

        if(response.headers["set-cookie"]){
          let setCookieArray = response.headers["set-cookie"];
          setCookieArray.forEach((setCookieItem,i,arr)=>{
            // 使用分号进行分割
            let contentArr = setCookieItem.split(";");
            let mainCookieItem = contentArr[0];
            let mainCookieItemContentArr = mainCookieItem.split("=");

            if(mainCookieItemContentArr.length > 0){
              ssoCookie[mainCookieItemContentArr[0]] = mainCookieItemContentArr[1];
            }
            console.log('!!!!!!!ssoCookie',ssoCookie);
          })
        }
        // res.send(body);

        // {
        //   "mobile":"YjNiMjA4NGJNVE0yTURZeU1UTXlNRGc9ZDI2YQ==",
        //   "password":"MzgwMTE1ZjZlSGN4TWpNME5UWT02NDEz",
        //   "key":"NzEzMDEyNmRjMkZzWlRFeU56ZzRMbmQ0TG14bGFuVXVZMjl0ODZmOA=="
        // }

        fs.writeFile(`/Users/zhaoqi/Downloads/sso_response_${new Date().getTime()}.json`,JSON.stringify(response),'utf8',function(error){
          if(error){
            console.log(error);
            return false;
          }
          console.log('写入成功');
        });

        let result = {
          responseBody: body,
          ssoCookie: ssoCookie
        };

        res.send(result);

      });
      // 返回数据
      // res.send(body);
    }catch(err){
      console.log(err);
      res.send(siteFunc.renderApiErr(req, res, 500, err, 'getlist'))
    }
  }

  async checkUser (req, res, next){
    try {

      console.log("~~~~MiaoSha~~~~checkUser");
      // for(let key in req){
      //   console.log('req key',key);
      // }

      // let params = req.body;

      let body = req.body;
      // let cookie = body.cookie;

      // console.log("~~~~MiaoSha~~~~checkUser req.body",req.body);
      // console.log("~~~~MiaoSha~~~~checkUser req.domain",req.domain);
      // console.log("~~~~MiaoSha~~~~checkUser req.headers",req.headers);
      // console.log("~~~~MiaoSha~~~~checkUser req.rawHeaders",req.rawHeaders);
      // console.log("~~~~MiaoSha~~~~checkUser req.rawTrailers",req.rawTrailers);
      // console.log("~~~~MiaoSha~~~~checkUser req.url",req.url);
      // console.log("~~~~MiaoSha~~~~checkUser req.params",req.params);
      // console.log("~~~~MiaoSha~~~~checkUser req.query",req.query);
      // console.log("~~~~MiaoSha~~~~checkUser req.param",req.param);

      // let username = params.username;
      // let password = params.password;
      // let activity_id = params.activity_id;
      // let project_id = params.project_id;

      // let username = 13606213208;      // 13606213208
      // let password = 0;                // xw123456
      // let activity_id = 12788;
      // let project_id = 32856;

      let username = body.userMsg.username;
      let password = body.userMsg.password;
      let activity_id = body.userMsg.activity_id;
      let project_id = body.userMsg.project_id;

      let cookie = body.userMsg.ssoCookie;

      let cookieString = '';

      for (let k in cookie) {
        cookieString += `${k}=${cookie[k]}; `;
      }

      // 向外发送请求
      await request({
        url: `http://sale${activity_id}.wx.leju.com/activity/sale/check_user_login_status.html?project_id=${project_id}&activity_id=${activity_id}`,
        // url: `http://weixin.leju.com/activity/sale/check_user_login_status.html?project_id=${project_id}&activity_id=${activity_id}`,
        method: "POST",
        json: true,
        headers: {
          "content-type": "application/x-www-form-urlencoded",
          "Cookie": cookieString
        },
      }, function(error, response, body) {
        console.log("~~~~MiaoSha~~~~checkUser success");
        console.log("~~~~MiaoSha~~~~checkUser success :::",body);

        if (!error && response.statusCode == 200) {
          console.log("~~~~MiaoSha~~~~checkUser success 200 body",body);
        }

        // res.send(body);
        let result = {
          responseBody: body,
        };

        res.send(result);

      });
      // 返回数据
      // res.send(body);
    }catch(err){
      console.log(err);
      res.send(siteFunc.renderApiErr(req, res, 500, err, 'getlist'))
    }
  }

  async kill (req, res, next){
    try {
      console.log("~~~~MiaoSha~~~~kill");
      let body = req.body;

      // fs.writeFile(`/Users/zhaoqi/Downloads/miaosha_kill_req_${new Date().getTime()}.json`,JSON.stringify(req.body),'utf8',function(error){
      //   if(error){
      //     console.log(error);
      //     return false;
      //   }
      //   console.log('写入成功');
      // });

      let activity_id = body.userMsg.activity_id;
      let project_id = body.userMsg.project_id;

      let cookie = body.userMsg.ssoCookie;

      let cookieString = '';

      for (let k in cookie) {
        cookieString += `${k}=${cookie[k]}; `;
      }

      console.log("!!!cookieString!!!",cookieString);

      // 向外发送请求
      await request({
        url: `http://sale${activity_id}.wx.leju.com/activity/sale/house_auction_list.html?project_id=${project_id}&activity_id=${activity_id}`,
        // url: `http://weixin.leju.com/activity/sale/house_auction_list.html?project_id=${project_id}&activity_id=${activity_id}`,
        method: "POST",
        json: true,
        headers: {
          "content-type": "application/x-www-form-urlencoded",
          "Cookie": cookieString
        },
      }, function(error, response, body) {
        console.log("~~~~MiaoSha~~~~kill success");
        console.log("~~~~MiaoSha~~~~kill success :::",body);

        if (!error && response.statusCode == 200) {
          console.log("~~~~MiaoSha~~~~kill success 200 body",body);
        }

        // res.send(body);
        let result = {
          responseBody: body,
        };

        res.send(result);

      });
      // 返回数据
      // res.send(body);
    }catch(err){
      console.log(err);
      res.send(siteFunc.renderApiErr(req, res, 500, err, 'getlist'))
    }
  }


  async trueKill (req, res, next){
    try {
      console.log("~~~~MiaoSha~~~~kill");
      let body = req.body;

      // fs.writeFile(`/Users/zhaoqi/Downloads/miaosha_kill_req_${new Date().getTime()}.json`,JSON.stringify(req.body),'utf8',function(error){
      //   if(error){
      //     console.log(error);
      //     return false;
      //   }
      //   console.log('写入成功');
      // });

      let activity_id = body.userMsg.activity_id;
      let project_id = body.userMsg.project_id;
      let vid = body.userMsg.vid;

      let cookie = body.userMsg.ssoCookie;

      let cookieString = '';

      for (let k in cookie) {
        cookieString += `${k}=${cookie[k]}; `;
      }

      console.log("!!!cookieString!!!",cookieString);

        // 向外发送请求
      await request({
        url: `http://sale${activity_id}.wx.leju.com/activity/sale/bidding.html`,
        // url: `http://sale${activity_id}.wx.leju.com/activity/sale/house_auction_list.html?project_id=${project_id}&activity_id=${activity_id}`,
        // url: `http://weixin.leju.com/activity/sale/house_auction_list.html?project_id=${project_id}&activity_id=${activity_id}`,
        method: "POST",
        json: true,
        form: {
          project_id: project_id,
          activity_id: activity_id,
          vid: vid,
          verify_code: '', // 需要构建
          // mobile: username,
          // image_code:'',
          // code:'',
          // card:'',
          // name:'',
          // activity_id: activity_id,
          // project_id: project_id,
        },
        headers: {
          "content-type": "application/x-www-form-urlencoded",
          "Cookie": cookieString
        },
      }, function(error, response, body) {
        console.log("~~~~MiaoSha~~~~TTkill success");
        console.log("~~~~MiaoSha~~~~TTkill success :::",body);

        if (!error && response.statusCode == 200) {
          console.log("~~~~MiaoSha~~~~TTkill success 200 body",body);
        }

        // res.send(body);
        let result = {
          responseBody: body,
        };

        res.send(result);

      });
      // 返回数据
      // res.send(body);
    }catch(err){
      console.log(err);
      res.send(siteFunc.renderApiErr(req, res, 500, err, 'getlist'))
    }
  }




}

module.exports = new MiaoSha();